package com.dream.myqiyi.ui;

import java.io.File;
import java.util.ArrayList;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.dream.myqiyi.BaseApp;
import com.dream.myqiyi.Global;
import com.dream.myqiyi.R;
import com.dream.myqiyi.dao.NoteModel;
import com.dream.myqiyi.image.util.ImageUtil;
import com.dream.myqiyi.service.ApplicationContext;
import com.dream.myqiyi.service.NoteService;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class NoteSearchActivity extends Activity {
	//private LinearLayout searchLayout = null;
	private ListView searchList = null;
	private String searchKeyword;
	private ArrayList<NoteModel> result = new ArrayList<NoteModel>();
	private NoteListAdapter adapter;		// 数据适配器

	private AutoCompleteTextView searchAutoEdit;//搜索文本框
	
	private TextView noSearchText;

	
	private static final int DIALOG_FIND = 2;

	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);  
		this.setContentView(R.layout.note_search_activity);
		
		initUI();
	}  
	
	private void initUI() {
		//searchLayout = (LinearLayout) this.findViewById(R.id.searchContent);

		// back
		this.findViewById(R.id.search_back_btn).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(NoteSearchActivity.this, NoteListActivity.class);
				startActivity(intent);
			}			
		});
		// search
		this.findViewById(R.id.search_btn).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				searchKeyword = searchAutoEdit.getText().toString();
				if (searchKeyword.equals("")) {
					BaseApp.showToast("请输入您要查找的内容");
				} else {
					//请求数据(从新执行一个任务)
					new SearchNoteTask().execute("");
				}
			}			
		});
		//搜索文本框
		searchAutoEdit=(AutoCompleteTextView) findViewById(R.id.search_Keywords);
		searchAutoEdit.addTextChangedListener(new TextWatcher() {

			@Override
			public void afterTextChanged(Editable arg0) {
				// TODO Auto-generated method stub
				searchKeyword = searchAutoEdit.getText().toString();
				if (searchKeyword.equals("")) {
					BaseApp.showToast("请输入您要查找的内容");
				} else {
					//请求数据(从新执行一个任务)
					new SearchNoteTask().execute("");
				}				
			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1,
					int arg2, int arg3) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {
				// TODO Auto-generated method stub
				
			}
			
		});
		//搜索结果
		noSearchText = (TextView)findViewById(R.id.no_search_tv);
		
		adapter = new NoteListAdapter(NoteSearchActivity.this, R.layout.list_child_item_note, result);
		searchList=(ListView) this.findViewById(R.id.searchlist);
		searchList.setAdapter(adapter);
		searchList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				//单击跳转到NoteView页面显示某一个tag的内容
				//从适配器中获取当前点击项的内容
				NoteModel note = result.get(position);

				Bundle bundle = new Bundle();
				bundle.putString("parent_ui", "note_list");
				bundle.putString("note_guid", note.getGuid());

				Intent intent = new Intent(NoteSearchActivity.this, NoteViewActivity.class);
				intent.putExtras(bundle);

				startActivity(intent);
			}
	
		});
	}
		
	// 弹出"查看"对话框
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DIALOG_FIND: {
			ProgressDialog dialog = new ProgressDialog(this);
			dialog.setMessage("正在查找...请稍候");
			dialog.setIndeterminate(true);
			dialog.setCancelable(true);
			return dialog;
		}
		}
		return null;
	}

	
	private class SearchNoteTask extends AsyncTask<String, String, String> {
		public String doInBackground(String... params) {
			NoteService noteSrv = (NoteService)ApplicationContext.getSingleton().getBean("NoteService");
			result.clear();
			if (noteSrv != null) {
				ArrayList<NoteModel> tags = noteSrv.getNotes();
				for (NoteModel tag : tags) {
					if (tag.getTitle().indexOf(searchKeyword) != -1 || tag.getContent().indexOf(searchKeyword) != -1) {
						result.add(tag);
					}
				}
			}
			return "";
		}

		@Override
		protected void onPreExecute() {
			showDialog(DIALOG_FIND);
			noSearchText.setVisibility(View.GONE);
		}

		@Override
		public void onPostExecute(String Re) {
			//绑定LISTVIEW
			removeDialog(DIALOG_FIND);
			
            //通知适配器，发现改变操作
			adapter.data = result;
            adapter.notifyDataSetChanged();	
            
            if (result.size() == 0) {
            	noSearchText.setVisibility(View.VISIBLE);
            }
		}
	}
	
	private class NoteListAdapter extends ArrayAdapter<NoteModel>{
		private ArrayList<NoteModel> data;
		private int layoutId;

		class NoteViewHolder {
			public CheckBox note_cb = null;
			public ImageView note_favorite_iv = null;
			public TextView  note_title_tv = null;
			public TextView  note_time_tv = null;
			public TextView  note_content_tv = null;
			public ImageView note_image_iv = null;

		}

		public NoteListAdapter(Activity a, int layout, ArrayList<NoteModel> d) {
			super(a, layout, d);
			data = d;
			layoutId = layout;
		}

		@Override
		public View getView(int position, View view, ViewGroup parent) {
			NoteViewHolder holder;
			if(view == null || (holder=(NoteViewHolder)view.getTag()) == null){
				holder = new NoteViewHolder();
				view = getLayoutInflater().inflate(layoutId, null);
				holder.note_cb = (CheckBox) view.findViewById(R.id.item_cb);
				holder.note_favorite_iv = (ImageView) view.findViewById(R.id.note_favorite_iv);
				holder.note_title_tv = (TextView) view.findViewById(R.id.note_title_tv);
				holder.note_time_tv = (TextView) view.findViewById(R.id.note_time_tv);
				holder.note_content_tv = (TextView) view.findViewById(R.id.note_content_tv);
				holder.note_image_iv = (ImageView) view.findViewById(R.id.note_image_iv);
				view.findViewById(R.id.list_note_title).setVisibility(View.GONE);
				view.setTag(holder);
			}
			holder.note_cb.setVisibility(View.GONE);
			// TODO
			holder.note_favorite_iv.setVisibility(View.GONE);
			final NoteModel newNote = data.get(position);
			if (newNote != null) {
				holder.note_title_tv.setText(newNote.getTitle());
				if (newNote.getUpdated() != 0) {
					holder.note_time_tv.setText(Global.DateFormat(newNote.getUpdated(), false));
				}

				Document document = Jsoup.parse(newNote.getContent());
				holder.note_content_tv.setText(document.body().getElementsByTag("p").text());
				final String imageFile = document.body().getElementsByTag("img").attr("src");

				if (Global.getResFileType(imageFile) == Global.RES_TYPE_IMAGE) {
					File image = new File(Global.resDir + imageFile);
					if (image.exists()) {
						holder.note_image_iv.setVisibility(View.VISIBLE);
						holder.note_image_iv.setImageBitmap(ImageUtil.scaleBitmap(Global.resDir + imageFile, 150, 150));
					} else {
						holder.note_image_iv.setVisibility(View.GONE);
					}
				} else {
					holder.note_image_iv.setVisibility(View.GONE);
				}
			}
			return view;
		}
	}
	



}
